<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="categoryId">
        <el-cascader :options="categoryOptions" ref="categoryCascader"
          :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'childCategoryList' }" clearable
          @change="handleCategoryChange" style="width: 300px" />
      </el-form-item>
      <el-form-item label="物品" prop="itemId">
        <el-select v-model="queryParams.itemId" filterable remote clearable placeholder="请输入关键词"
          :remote-method="queryItemStock" style="width: 450px;">
          <el-option v-for="item in itemOptions" :key="item.id" :label="item.name" :value="item.id">
            <el-row>
              <el-col :span="12">
                {{ item.name }}
              </el-col>
              <el-col :span="12">
                <el-tag type="info">{{ item.categoryName }}</el-tag>
              </el-col>
            </el-row>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="过期时间" prop="dateRule">
        <el-select v-model="queryParams.dateRule" placeholder="请选择过期时间" clearable>
          <el-option v-for="item in dateRuleOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="库存数量" prop="quantity">
        <el-select v-model="queryParams.quantity" placeholder="请选择库存数量" clearable style="width: 150px;">
          <el-option v-for="item in quantityOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="生产日期" prop="productDate">
        <el-date-picker clearable v-model="queryParams.productDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="过期时间" prop="expirationDate">
        <el-date-picker clearable v-model="queryParams.expirationDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择过期时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"">导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <ImagePreview :src="scope.row.item.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryName" width="300">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.item.categoryName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="item.name" width="200" />
      <el-table-column label="保质期" align="center" prop="shelfLife" width="70">
        <template slot-scope="scope">
          {{ scope.row.item.shelfLife + scope.row.item.unitString }}
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="quantity" width="70">
        <template slot-scope="scope">
          {{ scope.row.quantity }}
        </template>
      </el-table-column>
      <el-table-column label="重量" align="center" prop="weight" width="70" />
      <el-table-column label="剩余天数" align="center" prop="remainingDays" width="150">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.remainingDays < 45">{{ scope.row.remainingDays > 0 ?
            (scope.row.remainingDays + '天') : (-scope.row.remainingDays + '天前') }}</el-tag>
          <el-tag type="warning" v-else-if="scope.row.remainingDays < 120">{{ scope.row.remainingDays + '天' }}</el-tag>
          <el-tag type="success" v-else>{{ scope.row.remainingDays + '天' }}</el-tag>
          <el-progress :percentage="scope.row.percentage" :color="customColorMethod"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="productDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expirationDate" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="price" width="100" />
      <el-table-column label="购买价格" align="center" prop="purchasePrice" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改物品库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品" prop="itemId" v-if="title == '添加物品库存'">
          <el-select v-model="form.itemId" filterable remote clearable placeholder="请输入关键词"
            :remote-method="queryItemStock" style="width: 450px;">
            <el-option v-for="item in itemOptions" :key="item.id" :label="item.name" :value="item.id">
              <el-row>
                <el-col :span="8">
                  {{ item.name }}
                </el-col>
                <el-col :span="16">
                  <el-tag type="info">{{ item.categoryName }}</el-tag>
                </el-col>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :precision="0" :min="0" style="width: 150px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" clearable placeholder="请输入重量" style="width: 150px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="生产日期" prop="productDate">
          <el-date-picker clearable v-model="form.productDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原价" prop="price">
              <el-input-number v-model="form.price" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="购买价格" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItemStock, getItemStock, delItemStock, addItemStock, updateItemStock } from "@/api/itemStock"
import { tree } from "@/api/category"
import { listItem } from "@/api/item"
import Pagination from "@/components/Pagination"
import ImagePreview from "@/components/ImagePreview"

export default {
  name: "Stock",
  components: {
    Pagination,
    ImagePreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品库存表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 物品搜索栏
      itemOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        totalRow: -1,
        itemId: null,
        categoryId: null,
        quantity: 1,
        dateRule: null,
        productDate: null,
        expirationDate: null,
      },
      // 分类选择框
      categoryOptions: [],
      // 时间选择框
      dateRuleOptions: [
        { label: '已过期', key: 1 },
        { label: '未过期', key: 2 },
        { label: '一天内', key: 3 },
        { label: '一周内', key: 4 },
        { label: '一月内', key: 5 },
        { label: '三月内', key: 6 },
        { label: '半年内', key: 7 },
        { label: '一年内', key: 8 }
      ],
      quantityOptions: [
        { label: '有库存', key: 1 },
        { label: '无库存', key: 2 },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // itemId: [
        //   { required: true, message: "物品id不能为空", trigger: "blur" }
        // ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        productDate: [
          { required: true, message: "生产日期不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getTree()
    this.getList()
  },
  methods: {
    /** 查询分类列表 */
    getTree() {
      tree().then(response => {
        this.categoryOptions = response.data
      })
    },
    /** 查询物品 */
    queryItemStock(query) {
      if (query != null) {
        const params = {
          pageNum: 1,
          pageSize: 50,
          totalRow: -1,
          name: query,
        };
        listItem(params).then(response => {
          this.itemOptions = response.data.records
        })
      }
    },
    /** 查询物品库存列表 */
    getList() {
      this.loading = true
      listItemStock(this.queryParams).then(response => {
        this.stockList = response.data.records
        this.total = response.data.totalRow
        this.queryParams.totalRow = response.data.totalRow
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemId: null,
        quantity: null,
        productDate: null,
        expirationDate: null,
        createTime: null,
        updateTime: null
      }
      // this.resetForm("form")
    },
    /** 树形菜单按钮 */
    handleCategoryChange(value) {
      if (value != null && value.length > 0) {
        this.queryParams.categoryId = value[value.length - 1]
      } else {
        this.queryParams.categoryId = null
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.totalRow = -1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.$refs.categoryCascader.$refs.panel.checkedValue = []
      this.$refs.categoryCascader.$refs.panel.activePath = []
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(t => t.item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物品库存"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getItemStock(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物品库存"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.expirationDate = null;
            updateItemStock(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            if (this.form.itemId == null) {
              this.$refs["form"].validateField("itemId", callback => {
                this.$modal.msgError("请选择物品")
              })
            } else {
              addItemStock(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const names = row.item ? row.item.name : this.names
      this.$modal.confirm('是否确认删除物品名称为"' + names + '"的数据项？').then(function () {
        return delItemStock(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#f56c6c';
      } else if (percentage < 50) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    }
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('flex/stock/export', {
    //     ...this.queryParams
    //   }, `stock_${new Date().getTime()}.xlsx`)
    // }
  }
}
</script>